package com.mfc.education.service.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mfc.education.common.base.result.ResultCodeEnum;
import com.mfc.education.common.base.util.FormUtils;
import com.mfc.education.common.base.util.JwtInfo;
import com.mfc.education.common.base.util.JwtUtils;
import com.mfc.education.common.base.util.MD5;
import com.mfc.education.service.base.dto.MemberDto;
import com.mfc.education.service.base.exception.EduException;
import com.mfc.education.service.ucenter.entity.Member;
import com.mfc.education.service.ucenter.entity.vo.LoginVo;
import com.mfc.education.service.ucenter.entity.vo.RegisterVo;
import com.mfc.education.service.ucenter.mapper.MemberMapper;
import com.mfc.education.service.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Mfc
 * @since 2021-09-25
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${aliyun.oss.default-img}")
    private String defaultImg;


    @Override
    public boolean register(RegisterVo registerVo) {

        this.checkUser(registerVo);

        String email = registerVo.getEmail();
        String code = registerVo.getCode();
        String nickname = registerVo.getNickname();
        String password = registerVo.getPassword();

        Member member = new Member();
        member.setEmail(email);
        member.setNickname(nickname);
        member.setPassword(MD5.encrypt(password));
        member.setAvatar(defaultImg);
        member.setDisabled(false); //是否禁用用户
        // 保存用户
        boolean result = this.save(member);

        redisTemplate.delete(code);

        return result;
    }

    @Override
    public String login(LoginVo loginVo) {
        String email = loginVo.getEmail();
        String password = loginVo.getPassword();
        //校验参数
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || !FormUtils.isEmail(email)) {
            throw new EduException(ResultCodeEnum.PARAM_ERROR);
        }
        //校验邮箱
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        Member member = this.baseMapper.selectOne(queryWrapper);
        if (member == null) {
            throw new EduException(ResultCodeEnum.LOGIN_EMAIL_ERROR);
        }

        //校验密码
        if (!MD5.encrypt(password).equals(member.getPassword())) {
            throw new EduException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //检验用户是否被禁用

        if (member.getDisabled()) {
            throw new EduException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        String jwtToken = JwtUtils.getJwtToken(jwtInfo, 1800);

        return jwtToken;
    }

    @Override
    public Member getByOpenid(String openid) {

        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);

        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public MemberDto getMemberDtoByMemberId(String memberId) {
        Member member = baseMapper.selectById(memberId);
        MemberDto memberDto = new MemberDto();
        BeanUtils.copyProperties(member,memberDto);
        return memberDto;
    }

    @Override
    public Integer countRegisterNum(String day) {

        return baseMapper.selectRegisterNumByDay(day);
    }

    /**
     * 校验信息
     *
     * @param registerVo
     */
    private void checkUser(RegisterVo registerVo) {
        String email = registerVo.getEmail();
        String code = registerVo.getCode();
        String nickname = registerVo.getNickname();
        String password = registerVo.getPassword();
        // 1、校验qq邮箱是否合法
        if (StringUtils.isEmpty(email) || !FormUtils.isEmail(email)) {
            log.error("请输入正确的qq邮箱号");
            throw new EduException(ResultCodeEnum.LOGIN_EMAIL_ERROR);
        }
        // 2、对参数进行判空操作
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password)) {
            log.error("参数错误");
            throw new EduException(ResultCodeEnum.PARAM_ERROR);
        }
        // === 先校验验证码 再校验qq邮箱是否注册 会减轻数据库压力 ===
        // 3、校验验证码
        Object checkCode = redisTemplate.opsForValue().get(email);

        if (StringUtils.isEmpty(checkCode)) {
            log.error("邮箱验证码已过期");
            throw new EduException("邮箱验证码已过期", 28009);
        }
        if (!code.equals(checkCode)) {
            log.error("请输入正确的邮箱验证码");
            throw new EduException(ResultCodeEnum.CODE_ERROR);
        }

        // 4、校验qq邮箱是否注册
        boolean exists = this.isExists(email);
        if (exists) {
            log.error("qq邮箱已被注册");
            throw new EduException(ResultCodeEnum.REGISTER_EMAIL_ERROR);
        }


    }

    /**
     * 校验qq邮箱是否注册
     *
     * @param email
     * @return
     */
    private boolean isExists(String email) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count != 0;
    }
}
